using Android.App;
using Android.Content;
using Android.OS;
using Android.Views;
using Android.Widget;
using AF.Data;
using AF.Models;

namespace AF.Activities
{
    [Activity(Label = "项目管理", Theme = "@android:style/Theme.Material.Light.NoActionBar")]
    public class ProjectsActivity : Activity
    {
        private DatabaseHelper? dbHelper;
        private Button? btnAddProject;
        private ListView? listViewProjects;
        private TextView? textEmptyProjects;

        private List<Project> projects = new List<Project>();

        protected override void OnCreate(Bundle? savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_projects);

            dbHelper = new DatabaseHelper(this);

            InitializeViews();
            SetupEventHandlers();
        }

        protected override void OnResume()
        {
            base.OnResume();
            LoadProjects();
        }

        private void InitializeViews()
        {
            btnAddProject = FindViewById<Button>(Resource.Id.btnAddProject);
            listViewProjects = FindViewById<ListView>(Resource.Id.listViewProjects);
            textEmptyProjects = FindViewById<TextView>(Resource.Id.textEmptyProjects);
        }

        private void SetupEventHandlers()
        {
            if (btnAddProject != null)
            {
                btnAddProject.Click += (s, e) =>
                {
                    var intent = new Intent(this, typeof(AddProjectActivity));
                    StartActivity(intent);
                };
            }

            if (listViewProjects != null)
            {
                listViewProjects.ItemClick += (s, e) =>
                {
                    var project = projects[e.Position];
                    ShowProjectOptions(project);
                };
            }
        }

        private void LoadProjects()
        {
            if (dbHelper == null) return;

            projects = dbHelper.GetAllProjects();

            if (listViewProjects != null && textEmptyProjects != null)
            {
                if (projects.Count > 0)
                {
                    listViewProjects.Visibility = ViewStates.Visible;
                    textEmptyProjects.Visibility = ViewStates.Gone;

                    var adapter = new ProjectAdapter(this, projects, dbHelper);
                    listViewProjects.Adapter = adapter;
                }
                else
                {
                    listViewProjects.Visibility = ViewStates.Gone;
                    textEmptyProjects.Visibility = ViewStates.Visible;
                }
            }
        }

        private void ShowProjectOptions(Project project)
        {
            var items = new string[] { "查看详情", "项目统计", "删除项目" };

            new AlertDialog.Builder(this)!
                .SetTitle(project.Name)!
                .SetItems(items, (s, e) =>
                {
                    if (e.Which == 0)
                    {
                        ShowProjectDetails(project);
                    }
                    else if (e.Which == 1)
                    {
                        var intent = new Intent(this, typeof(ProjectDetailActivity));
                        intent.PutExtra("project_id", project.Id);
                        intent.PutExtra("project_name", project.Name);
                        StartActivity(intent);
                    }
                    else if (e.Which == 2)
                    {
                        ConfirmDeleteProject(project);
                    }
                })!
                .Show();
        }

        private void ShowProjectDetails(Project project)
        {
            string statusText = project.Status switch
            {
                ProjectStatus.InProgress => "进行中",
                ProjectStatus.Completed => "已完成",
                ProjectStatus.Paused => "已暂停",
                ProjectStatus.Cancelled => "已取消",
                _ => "未知"
            };

            string endDateText = project.EndDate.HasValue 
                ? project.EndDate.Value.ToString("yyyy-MM-dd") 
                : "进行中";

            string budgetText = project.Budget.HasValue 
                ? $"¥{project.Budget.Value:N2}" 
                : "未设置";

            string message = $"项目名称：{project.Name}\n" +
                           $"客户名称：{project.ClientName ?? "未填写"}\n" +
                           $"项目预算：{budgetText}\n" +
                           $"项目状态：{statusText}\n" +
                           $"开始日期：{project.StartDate:yyyy-MM-dd}\n" +
                           $"结束日期：{endDateText}\n" +
                           $"项目描述：{project.Description}\n" +
                           $"备注：{project.Remark ?? "无"}";

            new AlertDialog.Builder(this)!
                .SetTitle("项目详情")!
                .SetMessage(message)!
                .SetPositiveButton("确定", (s, e) => { })!
                .Show();
        }

        private void ConfirmDeleteProject(Project project)
        {
            if (dbHelper == null) return;

            var (income, expense, balance, count) = dbHelper.GetProjectStatistics(project.Id);

            string warningMessage = count > 0
                ? $"该项目有 {count} 条关联记录，删除后这些记录将不再关联到项目。\n\n确定要删除项目 {project.Name} 吗？"
                : $"确定要删除项目 {project.Name} 吗？";

            new AlertDialog.Builder(this)!
                .SetTitle("确认删除")!
                .SetMessage(warningMessage)!
                .SetPositiveButton("删除", (s, e) =>
                {
                    if (dbHelper != null)
                    {
                        int result = dbHelper.DeleteProject(project.Id);
                        if (result > 0)
                        {
                            Toast.MakeText(this, "删除成功", ToastLength.Short)?.Show();
                            LoadProjects();
                        }
                        else
                        {
                            Toast.MakeText(this, "删除失败", ToastLength.Short)?.Show();
                        }
                    }
                })!
                .SetNegativeButton("取消", (s, e) => { })!
                .Show();
        }
    }

    public class ProjectAdapter : BaseAdapter<Project>
    {
        private readonly Activity context;
        private readonly List<Project> items;
        private readonly DatabaseHelper dbHelper;

        public ProjectAdapter(Activity context, List<Project> items, DatabaseHelper dbHelper)
        {
            this.context = context;
            this.items = items;
            this.dbHelper = dbHelper;
        }

        public override Project this[int position] => items[position];

        public override int Count => items.Count;

        public override long GetItemId(int position) => position;

        public override View? GetView(int position, View? convertView, ViewGroup? parent)
        {
            var view = convertView ?? context.LayoutInflater.Inflate(
                Resource.Layout.list_item_project, null);

            var project = items[position];

            var textProjectName = view?.FindViewById<TextView>(Resource.Id.textProjectName);
            var textProjectStatus = view?.FindViewById<TextView>(Resource.Id.textProjectStatus);
            var textClientName = view?.FindViewById<TextView>(Resource.Id.textClientName);
            var textProjectDate = view?.FindViewById<TextView>(Resource.Id.textProjectDate);
            var textProjectIncome = view?.FindViewById<TextView>(Resource.Id.textProjectIncome);
            var textProjectExpense = view?.FindViewById<TextView>(Resource.Id.textProjectExpense);
            var textProjectBalance = view?.FindViewById<TextView>(Resource.Id.textProjectBalance);

            if (textProjectName != null)
                textProjectName.Text = project.Name;

            if (textProjectStatus != null)
            {
                string statusText = project.Status switch
                {
                    ProjectStatus.InProgress => "进行中",
                    ProjectStatus.Completed => "已完成",
                    ProjectStatus.Paused => "已暂停",
                    ProjectStatus.Cancelled => "已取消",
                    _ => "未知"
                };
                textProjectStatus.Text = statusText;

                var statusColor = project.Status switch
                {
                    ProjectStatus.InProgress => Android.Graphics.Color.ParseColor("#4CAF50"),
                    ProjectStatus.Completed => Android.Graphics.Color.ParseColor("#2196F3"),
                    ProjectStatus.Paused => Android.Graphics.Color.ParseColor("#FF9800"),
                    ProjectStatus.Cancelled => Android.Graphics.Color.ParseColor("#9E9E9E"),
                    _ => Android.Graphics.Color.ParseColor("#757575")
                };
                textProjectStatus.SetBackgroundColor(statusColor);
            }

            if (textClientName != null)
            {
                if (!string.IsNullOrWhiteSpace(project.ClientName))
                {
                    textClientName.Text = $"客户：{project.ClientName}";
                    textClientName.Visibility = ViewStates.Visible;
                }
                else
                {
                    textClientName.Visibility = ViewStates.Gone;
                }
            }

            if (textProjectDate != null)
            {
                string endDateText = project.EndDate.HasValue 
                    ? project.EndDate.Value.ToString("yyyy-MM-dd") 
                    : "进行中";
                textProjectDate.Text = $"{project.StartDate:yyyy-MM-dd} ~ {endDateText}";
            }

            // 获取项目统计
            var (income, expense, balance, count) = dbHelper.GetProjectStatistics(project.Id);

            if (textProjectIncome != null)
                textProjectIncome.Text = $"¥{income:N2}";

            if (textProjectExpense != null)
                textProjectExpense.Text = $"¥{expense:N2}";

            if (textProjectBalance != null)
                textProjectBalance.Text = $"¥{balance:N2}";

            return view;
        }
    }
}

